﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using SlaughterItem.Common.Domains.Check_Ins;
using SlaughterItem.Common.Dtos;
using SlaughterItem.Common.Infrastructures.Interfaces;
using SlaughterItem.Enum;

namespace GetSlaughterItem.API.Application.Commands.Week02.Check_In
{
    /// <summary>
    /// 点击进场表进行页面跳转，根据进场编号查询进场信息
    /// </summary>
    public class CheckInNoSelectHandler : IRequestHandler<CheckInNoSelectCommand, Result>
    {
        IBaseRepositoryGet<CheckIn> CheckInRep;
        IBaseRepositoryGet<CheckInState> CheckInStateRep;
        IBaseRepositoryGet<SettlementType> SettlementTypeRep;
        IBaseRepositoryGet<Supplier> SupplierRep;

        public CheckInNoSelectHandler(IBaseRepositoryGet<CheckIn> checkInRep, IBaseRepositoryGet<CheckInState> checkInStateRep, IBaseRepositoryGet<SettlementType> settlementTypeRep, IBaseRepositoryGet<Supplier> supplierRep)
        {
            CheckInRep = checkInRep;
            CheckInStateRep = checkInStateRep;
            SettlementTypeRep = settlementTypeRep;
            SupplierRep = supplierRep;
        }

        public async Task<Result> Handle(CheckInNoSelectCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var list = from a in CheckInRep.GetAll()
                           join b in SupplierRep.GetAll()
                           on a.SupplierId equals b.SupplierId
                           join c in SettlementTypeRep.GetAll()
                           on a.SettlementTypeId equals c.SettlementTypeId
                           select new
                           {
                               a.CheckInId,
                               a.CheckInNo,
                               a.CarNo,
                               b.SupplierName,
                               c.SettlementTypeName,
                               a.OriginAddr,
                               a.ApproachNum,
                           };
                if (!string.IsNullOrEmpty(request.CheckInNo))
                {
                    list = list.Where(x => x.CheckInNo == request.CheckInNo);
                }
                if (list != null)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = list;
                    result.Msg = "成功";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
